// index.js
const generator = require('../../utils/sudoku-generator.js');
const solver = require('../../utils/sudoku-solver.js');
const storage = require('../../utils/storage.js');
const cloudService = require('../../utils/cloud/cloudService.js');

Page({
  data: {
    sudokuBoard: [],        // 当前数独棋盘（对象数组）
    initialBoard: [],       // 初始题目（纯数字数组）
    solutionBoard: [],      // 答案（纯数字数组）
    isSolving: false,       // 是否正在求解
    isSolved: false,        // 是否已解决
    steps: 0,               // 求解步数
    backtracks: 0,          // 回溯次数
    solveSpeed: 100,        // 求解速度（毫秒）
    difficulty: 'medium',   // 难度
    stopSolving: false,     // 终止求解标志
    drawerVisible: false,   // 抽屉是否可见
    userInfo: {},           // 用户信息
    startTime: null         // 开始时间（用于计算用时）
  },

  onLoad() {
    console.log('页面加载，开始生成题目');
    console.log('generator:', generator);
    console.log('solver:', solver);
    
    // 加载设置
    this.loadSettings();
    
    // 加载用户信息
    this.loadUserInfo();
    
    // 页面加载时生成一个新题目
    this.generateNewGame();
  },

  onShow() {
    // 每次显示页面时重新加载设置（从设置页面返回时会更新）
    this.loadSettings();
  },

  /**
   * 加载设置
   */
  loadSettings() {
    const settings = wx.getStorageSync('gameSettings') || {};
    this.setData({
      solveSpeed: settings.solveSpeed || 100,
      difficulty: settings.difficulty || 'medium'
    });
  },

  /**
   * 加载用户信息
   */
  loadUserInfo() {
    const userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      this.setData({ userInfo });
    }
  },

  /**
   * 打开抽屉
   */
  openDrawer() {
    this.setData({ drawerVisible: true });
  },

  /**
   * 关闭抽屉
   */
  closeDrawer() {
    this.setData({ drawerVisible: false });
  },

  /**
   * 处理登录
   */
  async handleLogin() {
    wx.showLoading({ title: '登录中...' })
    
    try {
      // 获取用户信息
      const profileRes = await wx.getUserProfile({
        desc: '用于完善用户资料'
      })
      
      const userInfo = profileRes.userInfo
      
      // 云端登录
      const loginResult = await cloudService.login({
        nickName: userInfo.nickName,
        avatarUrl: userInfo.avatarUrl,
        gender: userInfo.gender
      })
      
      wx.hideLoading()
      
      if (loginResult.success) {
        // 保存本地用户信息
        const fullUserInfo = {
          ...userInfo,
          ...loginResult.data,
          userId: loginResult.data.userId
        }
        
        wx.setStorageSync('userInfo', fullUserInfo)
        
        this.setData({ 
          userInfo: fullUserInfo,
          drawerVisible: false
        })
        
        // 显示欢迎提示
        if (loginResult.data.isNewUser) {
          wx.showModal({
            title: '欢迎新玩家！',
            content: `你已成功注册，当前等级 ${loginResult.data.level}`,
            showCancel: false
          })
        } else {
          wx.showToast({
            title: '登录成功',
            icon: 'success'
          })
        }
      } else {
        wx.showToast({
          title: '云端登录失败',
          icon: 'none'
        })
      }
    } catch (err) {
      wx.hideLoading()
      console.error('登录失败:', err)
      wx.showToast({
        title: '登录失败',
        icon: 'error'
      })
    }
  },

  /**
   * 处理退出登录
   */
  handleLogout() {
    wx.removeStorageSync('userInfo');
    this.setData({ 
      userInfo: {}
    });
    
    wx.showToast({
      title: '已退出登录',
      icon: 'success'
    });
  },

  /**
   * 生成新题目
   */
  generateNewGame() {
    wx.showLoading({
      title: '生成题目中...',
    });

    // 延迟一下让加载动画显示
    setTimeout(() => {
      try {
        // 生成数独题目
        const { puzzle, solution } = generator.generateSudoku(this.data.difficulty);
        
        // 保存初始题目和答案
        this.setData({
          initialBoard: puzzle.map(row => [...row]),
          solutionBoard: solution.map(row => [...row]),
          sudokuBoard: generator.boardToObjects(puzzle, puzzle),
          isSolved: false,
          steps: 0,
          backtracks: 0,
          startTime: Date.now() // 记录开始时间
        });

        wx.hideLoading();
        wx.showToast({
          title: '题目已生成',
          icon: 'success',
          duration: 1500
        });
      } catch (error) {
        wx.hideLoading();
        wx.showToast({
          title: '生成失败',
          icon: 'error'
        });
        console.error('生成数独失败:', error);
      }
    }, 300);
  },

  /**
   * 开始求解
   */
  async startSolve() {
    if (this.data.isSolving) return;

    this.setData({
      isSolving: true,
      stopSolving: false,
      steps: 0,
      backtracks: 0
    });

    // 重置到初始状态
    const board = this.data.initialBoard.map(row => [...row]);
    
    try {
      // 使用可视化求解
      const result = await solver.solveSudokuWithVisualization(
        board,
        this.onSolveStep.bind(this),
        this.data.solveSpeed,
        () => this.data.stopSolving  // 传入终止检查函数
      );

      // 检查是否被终止
      if (this.data.stopSolving) {
        this.setData({
          isSolving: false
        });
        wx.showToast({
          title: '已终止求解',
          icon: 'none',
          duration: 1500
        });
        return;
      }

      // 求解完成
      this.setData({
        isSolving: false,
        isSolved: result
      });

      if (result) {
        // 保存游戏记录
        const gameRecord = {
          id: Date.now(),
          timestamp: Date.now(),
          duration: Math.floor((Date.now() - this.data.startTime) / 1000),
          steps: this.data.steps,
          backtracks: this.data.backtracks,
          success: true,
          solveType: 'auto',
          difficulty: this.data.difficulty
        }
        
        // 保存到本地
        storage.saveGameRecord(gameRecord)
        
        // 同步到云端
        cloudService.syncGameRecord(gameRecord).catch(err => {
          console.warn('云端同步失败:', err)
        })

        wx.showToast({
          title: '求解完成！',
          icon: 'success',
          duration: 2000
        });
      } else {
        wx.showToast({
          title: '无解',
          icon: 'error',
          duration: 2000
        });
      }
    } catch (error) {
      console.error('求解失败:', error);
      wx.showToast({
        title: '求解失败',
        icon: 'error'
      });
      this.setData({
        isSolving: false
      });
    }
  },

  /**
   * 终止求解
   */
  stopSolve() {
    this.setData({
      stopSolving: true
    });
    wx.showToast({
      title: '正在终止...',
      icon: 'loading',
      duration: 1000
    });
  },

  /**
   * 求解过程回调（可视化）
   */
  async onSolveStep(stepInfo) {
    const { type, row, col, value, board } = stepInfo;
    
    // 更新统计
    if (type === 'forward') {
      this.setData({
        steps: this.data.steps + 1
      });
    } else if (type === 'backtrack') {
      this.setData({
        backtracks: this.data.backtracks + 1
      });
    }

    // 更新棋盘显示
    const sudokuBoard = this.data.sudokuBoard.map((row, r) =>
      row.map((cell, c) => {
        const newCell = { ...cell };
        
        // 更新值
        if (board[r][c] !== cell.value) {
          newCell.value = board[r][c];
        }
        
        // 高亮当前操作位置
        newCell.isCurrent = (r === row && c === col);
        
        // 回溯动画
        newCell.isBacktrack = (type === 'backtrack' && r === row && c === col);
        
        return newCell;
      })
    );

    this.setData({
      sudokuBoard: sudokuBoard
    });

    // 清除回溯高亮
    if (type === 'backtrack') {
      setTimeout(() => {
        const board = this.data.sudokuBoard.map(row =>
          row.map(cell => ({
            ...cell,
            isBacktrack: false
          }))
        );
        this.setData({
          sudokuBoard: board
        });
      }, 200);
    }
  },

  /**
   * 重置游戏
   */
  resetGame() {
    this.setData({
      sudokuBoard: generator.boardToObjects(this.data.initialBoard, this.data.initialBoard),
      isSolved: false,
      steps: 0,
      backtracks: 0
    });

    wx.showToast({
      title: '已重置',
      icon: 'success',
      duration: 1000
    });
  },

  /**
   * 用户输入数字
   */
  onCellInput(e) {
    const { row, col } = e.currentTarget.dataset;
    let value = parseInt(e.detail.value) || 0;
    
    // 限制在1-9之间
    if (value < 0 || value > 9) {
      value = 0;
    }

    // 更新棋盘
    const sudokuBoard = this.data.sudokuBoard;
    sudokuBoard[row][col].value = value;
    
    // 检查该数字是否有效（只检查数独规则，不依赖答案）
    if (value !== 0) {
      const board = sudokuBoard.map(r => r.map(c => c.value));
      const isValidInput = solver.isValidUserInput(board, row, col, value);
      sudokuBoard[row][col].isError = !isValidInput;
    } else {
      sudokuBoard[row][col].isError = false;
    }
    
    this.setData({
      sudokuBoard: sudokuBoard
    });

    // 检查是否完成
    if (this.checkIfComplete()) {
      // 保存游戏记录
      const gameRecord = {
        id: Date.now(),
        timestamp: Date.now(),
        duration: Math.floor((Date.now() - this.data.startTime) / 1000),
        steps: this.data.steps,
        success: true,
        solveType: 'manual',
        difficulty: this.data.difficulty
      }
      
      // 保存到本地
      storage.saveGameRecord(gameRecord)
      
      // 同步到云端
      cloudService.syncGameRecord(gameRecord).catch(err => {
        console.warn('云端同步失败:', err)
      })

      wx.showToast({
        title: '恭喜完成！',
        icon: 'success'
      });
      this.setData({
        isSolved: true
      });
    }
  },

  /**
   * 点击单元格
   */
  onCellTap(e) {
    // 可以在这里添加选中效果等
  },

  /**
   * 检查是否完成
   */
  checkIfComplete() {
    const board = this.data.sudokuBoard.map(row => 
      row.map(cell => cell.value)
    );
    return solver.isSolved(board);
  }
})
